package com.sniff.atp.utils;

import com.alibaba.fastjson2.*;
import com.google.gson.Gson;
import com.sniff.atp.dto.ContentDTO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class JsonUtil {

    private JsonUtil(){}


    /**
     * fileName 文件名，可以带后缀，也可以不带后缀
     * content 需要替换的内容，示例：${xxx}，source：xxx，target为需要替换的值：123
     */
    public static JSONObject readJson(String fileName, ContentDTO... contents) {
        String path = "json/" + fileName.split("\\.")[0] + ".json";
        Resource resource = new ClassPathResource(path);
        JSONObject json;
        try (InputStream inputStream = resource.getInputStream()) {
            String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            if (contents.length > 0) {
                for (ContentDTO content : contents) {
                    str = str.replace("${" + content.source() + "}", content.target());
                }
            }
            json = JSON.parseObject(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * fileName 文件名，可以带后缀，也可以不带后缀
     * content 需要替换的内容，示例：${xxx}，source：xxx，target为需要替换的值：123
     */
    public static JSONArray readJSONArray(String fileName, ContentDTO... contents) {
        String path = "json/" + fileName.split("\\.")[0] + ".json";
        Resource resource = new ClassPathResource(path);
        JSONArray json = null;
        try (InputStream inputStream = resource.getInputStream()) {
            String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            if (contents.length > 0) {
                for (ContentDTO content : contents) {
                    str = str.replace("${" + content.source() + "}", content.target());
                }
            }
            json = JSON.parseArray(str);
        } catch (IOException e) {
            LogUtil.error(e.getMessage());
        }
        return json;
    }

    /**
     * JSON字符串提取
     *
     * @param json 需提取的json字符串
     * @param reg  提取表达式，示例：{"code":"0","msg":"1","data":{"a":"2"}}, data.a就可以提取出a的值
     * @return 返回一个Object对象
     */
    public static Object extract(String json, String reg) {
        return JSONPath.extract(json, "$." + reg);
    }

    /**
     * JSON字符串提取
     * 返回值为String
     */
    public static String extractString(String json, String reg) {
        return String.valueOf(JSONPath.extract(json, "$." + reg));
    }

    /**
     * JSON字符串提取
     * 返回值为String
     */
    public static BigDecimal extractBigDecimal(String json, String reg) {
        return new BigDecimal(extractString(json, reg));
    }

    /**
     * JSON数字提取
     * 返回值为Integer
     */
    public static Integer extractInteger(String json, String reg) {
        return Integer.valueOf(extractString(json, reg));
    }

    /**
     * JSONArray提取
     * 返回值为JSONArray
     */
    public static JSONArray extractJSONArray(String json, String reg) {
        return JSON.parseArray(String.valueOf(JSONPath.extract(json, "$." + reg)));
    }

    /**
     * JSONObject提取
     * 返回值为JSONObject
     */
    public static JSONObject extractJSONObject(String json, String reg) {
        return JSON.parseObject(extractString(json, reg));
    }

    /**
     * JSON字符串提取
     * 返回值为多个命中的值
     */
    public static JSONArray extractMulti(String json, String reg) {
        return (JSONArray) JSONPath.extract(json, "$.." + reg);
    }

    public static <T> List<T> extractMultiT(String json, String reg) {
        return (List<T>) JSONPath.extract(json, "$.." + reg);
    }

    public static <T> List<T> extractMultiList(String json, String reg) {
        return (List<T>) JSONPath.extract(json, "$." + reg);
    }

    public static <T> T parseObject(String json, String key, Class<T> clazz) {
        return JSON.parseObject(json).getObject(key, clazz);
    }

    /**
     * 遍历一个JSONArray，获取匹配到某一个属性的JSONObject
     *
     * @param key   JSONObject属性
     * @param value JSONObject属性匹配上的值
     * @return 返回匹配到属性的对象
     */
    public static JSONObject findJSONArray(JSONArray jsonArray, String key, String value) {
        JSONObject jsonObject = null;
        if (Objects.isNull(jsonArray)) {
            return null;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            String[] keys = key.split("\\.");
            if (jsonArray.getJSONObject(i).get(keys[0]) instanceof JSONArray) {
                return findJSONArray(jsonArray.getJSONObject(i).getJSONArray(keys[0]), keys[1], value);
            } else {
                jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.getString(keys[0]).equals(value)) {
                    return jsonObject;
                }
            }
        }
        return jsonObject;
    }

    /**
     * JSONArray中某一个属性的值求和
     */
    public static BigDecimal sumJSONArray(JSONArray jsonArray, String key) {
        BigDecimal bigDecimal = new BigDecimal("0.00");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (Objects.nonNull(jsonObject.getBigDecimal(key))) {
                bigDecimal = bigDecimal.add(jsonObject.getBigDecimal(key));
            }
        }
        return bigDecimal;
    }

    /**
     * 订单金额计算
     */
    public static BigDecimal sumPriceOrder(JSONArray jsonArray) {
        BigDecimal bigDecimal = new BigDecimal("0.00");
        String key = "actualTotalProductSellPrice";
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String temp = jsonObject.toJSONString();
            BigDecimal sellQuantity = extractBigDecimal(temp, "sellQuantity");
            if (Objects.nonNull(jsonObject.getBigDecimal(key))) {
                bigDecimal = bigDecimal.add(jsonObject.getBigDecimal(key));
            }
            if (!CollectionUtils.isEmpty(jsonObject.getJSONArray("platformOrderItemAdditionDTOList"))) {
                String additionItems = jsonObject.getJSONArray("platformOrderItemAdditionDTOList").toString();
                List<Object> additionCosts = (JSONArray) JSONPath.extract(additionItems, "$..cost");
                BigDecimal additionCostsSum = additionCosts.stream().map(cost -> new BigDecimal(cost + "")).reduce(BigDecimal.ZERO, BigDecimal::add);
                bigDecimal = bigDecimal.add(sellQuantity.multiply(additionCostsSum));
            }
            if (!CollectionUtils.isEmpty(jsonObject.getJSONArray("combinationOrderItemList"))) {
                JSONArray combinationOrderItemList = jsonObject.getJSONArray("combinationOrderItemList");
                for (int j = 0; j < combinationOrderItemList.size(); j++) {
                    String combinationOrderItem = combinationOrderItemList.getJSONObject(j).toJSONString();
                    List<Object> costs = (JSONArray) JSONPath.extract(combinationOrderItem, "$..platformOrderItemAdditionDTOList.cost");
                    BigDecimal subSellQuantity = extractBigDecimal(combinationOrderItem, "sellQuantity");
                    if (CollectionUtils.isEmpty(costs)) {
                        continue;
                    }
                    BigDecimal costSum = costs.stream().map(cost -> new BigDecimal(cost + "")).reduce(BigDecimal.ZERO, BigDecimal::add);
                    bigDecimal = bigDecimal.add(subSellQuantity.multiply(costSum));
                }
            }
        }
        return bigDecimal;
    }

    /**
     * 字符串转json
     */
    public static JSONObject strToJSONObject(String data) {
        return JSONObject.parseObject(data, JSONObject.class);
    }

    /**
     * 支付串转json数组
     */
    public static JSONArray strToJSONArray(String data) {
        return JSONArray.of(data);
    }

    /**
     * 读取数据json
     *
     * @param fileName
     * @return
     */
    public static JSONObject readFileJson(String fileName) {
        String path = "classpath:" + fileName.split("\\.")[0] + ".json";
        JSONObject json;
        try {
            String str = FileUtils.readFileToString(ResourceUtils.getFile(path), StandardCharsets.UTF_8);
            json = JSON.parseObject(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * 读取数据json
     *
     * @param fileName
     * @return
     */
    public static JSONArray readFileJSONArray(String fileName) {
        String path = "classpath:" + fileName.split("\\.")[0] + ".json";
        JSONArray json;
        try {
            String str = FileUtils.readFileToString(ResourceUtils.getFile(path), StandardCharsets.UTF_8);
            json = JSON.parseArray(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return json;
    }
    /**
     * mapStr转为Map类型
     * @param mapStr
     * @return
     * @throws JSONException
     */
    public static Map<String,String> mapStr2Map(String mapStr) throws JSONException {
        mapStr = mapStr.substring(1, mapStr.length()-1);
        String[] strs = mapStr.split(",");
        Map<String,String> map = new HashMap<>();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            // 去掉头部空格
            String key1 = key.trim();
            String value1 = value.trim();
            map.put(key1, value1);
        }
        return map;
    }

    /**
     * jsoStr转为Map类型
     * @param jsonStr
     * @return
     * @throws JSONException
     */
    public static Map<String,String> jsoStr2Map(String jsonStr) throws JSONException {
        Gson gson = new Gson();
        return gson.fromJson(jsonStr, HashMap.class);
    }
}
